package com.alibaba.aliper.agent.basher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import com.alibaba.aliper.server.interfaces.AliperRemoteControll;
import com.caucho.hessian.client.HessianProxyFactory;

public class SendWords {

	@Option(name = "-server", usage = "server ip or name. default is localhost", required = false)
	private String serverIp = "localhost";
	
	@Option(name = "-port", usage = "server port. default is 8080.", required = false)
	private String port = "8080";
	
	@Option(name = "-project", usage = "project. default is project.", required = false)
	private String project = "project";
	
	@Option(name = "-agent", usage = "agent name. default is server ip.", required = false)
	private String agent = null;
	
	@Option(name = "-chart", usage = "chart name. ", required = true)
	private String chart = null;
	
	private AliperRemoteControll remote = null;
	
	public static void main(String[] args) throws IOException {
		SendWords sendWords = new SendWords();
		CmdLineParser cmdLineParser = new CmdLineParser(sendWords);
		try {
			cmdLineParser.parseArgument(args);
		} catch (CmdLineException e) {
			System.err.println(e.getMessage());
			System.out.println("Usage:");
			cmdLineParser.printUsage(System.out);
			return;
		}
		sendWords.send();
	}
	
	private String[] headers = null;

	public void send() throws IOException {
		if(agent == null){
	    	 agent = InetAddress.getLocalHost().getHostAddress();
	     }
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		String line = null;
		this.headers = getWords(reader.readLine());
		while((line = reader.readLine()) != null){
			this.sendLine(line);
		}
	}

	private void sendLine(String line) {
		String[] words = getWords(line);
		int index = 0;
		long time = System.currentTimeMillis();
		for(String word : words){
			try{
				double value = Double.parseDouble(word);
				if(remote == null){
					HessianProxyFactory factory = new HessianProxyFactory();
					remote = (AliperRemoteControll) factory.create(AliperRemoteControll.class, "http://"+this.serverIp+":"+this.port+"/aliper-server/AliperServlet");
				}
				if(index < words.length){
					remote.report(project,agent, chart, headers[index], time, value);
				}
			} catch (Exception e) {
				System.err.println(e);
			} finally{
				index++;
			}
		}
	}

	private static String[] getWords(String line) {
		if(line == null)
			throw new NullPointerException("headers can not be null");
		line = line.replaceAll("\\s+", "&&");
		if(line.startsWith("&&")){
			line = line.substring(2);
		}
		if(line.endsWith("&&")){
			line = line.substring(0, line.length()-2);
		}
		return line.split("&&");
	}

}
